package com.qfedu.knowledge.controller;

import com.google.code.kaptcha.Producer;
import com.qfedu.knowledge.entity.vo.ResultVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName CaptchaController
 * @Author ykx
 * @Date 2024/5/21 15:12
 * @Version 1.0
 */
@RestController
@RequestMapping("/knowledge")
public class CaptchaController {

    @Autowired
    private Producer producer;

    /**
     * 生成验证码
     *
     * @return
     * @throws Exception
     */
    @GetMapping("/captcha")
    public ResultVO captcha(HttpServletRequest request) throws Exception {
        String code = producer.createText();

        System.out.println("code=" + code);
        request.getSession().setAttribute("kaptcha", code);

        BufferedImage image = producer.createImage(code);
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ImageIO.write(image, "jpg", outputStream);

        BASE64Encoder encoder = new BASE64Encoder();
        String str = "data:image/jpeg;base64,";

        String base64Img = str + encoder.encode(outputStream.toByteArray());

        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("base64Img", base64Img);
        return ResultVO.success(resultMap);
    }
}
